package net.zio.kamenriderzioaddon.ridersystem.data;

import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.common.util.INBTSerializable;
import net.zio.kamenriderzioaddon.enums.HenshinState;
import net.zio.kamenriderzioaddon.network.NetworkHandler;
import net.zio.kamenriderzioaddon.network.message.SyncPlayerDataPacket;
import net.zio.kamenriderzioaddon.ridersystem.registry.AwakeningConfig;
import net.zio.kamenriderzioaddon.ridersystem.registry.BaseRiderConfig;
import net.zio.kamenriderzioaddon.ridersystem.registry.FullRiderConfig;
import net.zio.kamenriderzioaddon.ridersystem.registry.RiderConfigRegistry;
import net.zio.kamenriderzioaddon.ridersystem.util.HenshinUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 玩家数据管理器类
 *
 * @author QianYunYi
 * 该类负责管理玩家的变身数据，包括变身状态、强化形态、待机状态等。
 */
public class PlayerDataManager implements INBTSerializable<CompoundTag> {

    // 服务器实例
    private static final Map<UUID, PlayerDataManager> SERVER_INSTANCES = new HashMap<>();
    // 客户端实例
    private static final Map<UUID, PlayerDataManager> CLIENT_INSTANCES = new HashMap<>();
    // 玩家变身状态
    private HenshinState currentState = HenshinState.INACTIVE;
    // 变身的骑士名称
    private String activeRiderName = "";
    // 强化形态名称
    private String activeAwakeningName = "";
    // 待机状态存储
    private CompoundTag standbyGear = new CompoundTag();
    // 变身状态存储
    private CompoundTag activeGear = new CompoundTag();
    // 同步标志
    private boolean needsSync = false;
    // 保存标志
    private boolean needsSave = false;
    // 玩家 UUID
    private final UUID playerId;
    // 客户端标志
    private final boolean isClientSide;
    // 变身状态
    private boolean isHenshining = false;
    // 状态恢复标志
    private boolean needsStateRestore = false;

    // 获取是否处于变身中的状态
    public boolean isHenshining() {
        return isHenshining;
    }

    // 设置变身中状态
    public void setHenshining(boolean value) {
        this.isHenshining = value;
    }

    // 获取是当前玩家的变身状态
    public HenshinState getCurrentState() {
        return currentState;
    }

    // 设置玩家的当前变身状态
    public void setCurrentState(HenshinState state) {
        this.currentState = state;
        markDirty();
    }

    // 获取状态恢复标志
    public boolean needsStateRestore() {
        return this.needsStateRestore;
    }

    // 设置状态恢复标志
    public void setNeedsStateRestore(boolean value) {
        this.needsStateRestore = value;
    }

    /**
     * 玩家数据管理器构造函数
     *
     * @param player 玩家实例
     */
    private PlayerDataManager(Player player) {
        this.playerId = player.getUUID();
        this.isClientSide = player.level.isClientSide;
    }

    /**
     * 玩家数据管理器更新方法
     *
     * @param player 玩家实例
     */
    public void tick(Player player) {
        if (player.level.isClientSide) return;

        /*// 检查是否需要恢复状态
        if (needsStateRestore) {
            restorePlayerState(player);
            needsStateRestore = false;
        }*/

        // 检查是否需要保存
        if (needsSave) {
            saveToPlayer(player);
            needsSave = false;
        }

        // 检查是否需要同步
        if (needsSync) {
            sync(player);
            needsSync = false;
        }
    }

    /**
     * 同步玩家数据到客户端
     *
     * @param player 玩家实例
     */
    public void syncToTrackingPlayers(Player player) {
        if (player instanceof ServerPlayer serverPlayer) {
            NetworkHandler.sendToTrackingPlayers(
                    new SyncPlayerDataPacket(serializeNBT(), player.getUUID()),
                    serverPlayer
            );
        }
    }

    /**
     * 获取玩家数据管理器实例
     *
     * @param player 玩家实例
     * @return 玩家数据管理器实例
     */
    public static PlayerDataManager get(Player player) {
        if (player.level.isClientSide) {
            return CLIENT_INSTANCES.computeIfAbsent(player.getUUID(), id -> {
                PlayerDataManager newInstance = new PlayerDataManager(player);
                newInstance.loadFromPlayer(player);
                return newInstance;
            });
        } else {
            return SERVER_INSTANCES.computeIfAbsent(player.getUUID(), id -> {
                PlayerDataManager newInstance = new PlayerDataManager(player);
                newInstance.loadFromPlayer(player);
                return newInstance;
            });
        }
    }

    /**
     * 获取客户端玩家数据管理器实例
     *
     * @return 客户端玩家数据管理器实例
     */
    public static PlayerDataManager getClientPlayer() {
        Player player = Minecraft.getInstance().player;
        return player != null ? get(player) : null;
    }

    /**
     * 获取玩家的变身状态
     *
     * @param config 骑士配置
     * @return 玩家的变身状态
     */
    public HenshinState getRiderState(BaseRiderConfig config) {
        if (!config.getRiderName().equals(activeRiderName)) {
            return HenshinState.INACTIVE;
        }

        // 如果是强化形态配置
        if (config instanceof FullRiderConfig fullConfig) {
            if (fullConfig.hasAwakeningConfig(activeAwakeningName)) {
                return currentState;
            }
        }

        // 基础形态
        return currentState;
    }

    // 设置强化形态
    public void setActiveAwakening(String awakeningName) {
        this.activeAwakeningName = awakeningName;
        markDirty();
    }


    /**
     * 设置玩家的变身状态
     *
     * @param config 骑士配置
     * @param state  新的变身状态
     */
    public void setRiderState(BaseRiderConfig config, HenshinState state) {
        this.activeRiderName = config.getRiderName();
        this.currentState = state;
        markDirty();
    }

    /**
     * 获取待机状态存储
     *
     * @return 待机状态存储
     */
    public CompoundTag getStandbyGear() {
        return standbyGear;
    }

    /**
     * 设置待机状态存储
     *
     * @param gearData 新的待机状态存储
     */
    public void setStandbyGear(CompoundTag gearData) {
        this.standbyGear = gearData;
        markDirty();
    }

    /**
     * 获取变身状态存储
     *
     * @return 变身状态存储
     */
    public CompoundTag getActiveGear() {
        return activeGear;
    }

    /**
     * 设置变身状态存储
     *
     * @param gearData 新的变身状态存储
     */
    public void setActiveGear(CompoundTag gearData) {
        this.activeGear = gearData;
        markDirty();
    }

    // 清除变身数据
    public void clearGearData() {
        this.standbyGear = new CompoundTag();
        this.activeGear = new CompoundTag();
        markDirty();
    }

    /**
     * 获取当前变身骑士的名称
     *
     * @return 当前变身骑士的名称
     */
    public String getActiveRiderName() {
        return activeRiderName;
    }

    /**
     * 获取当前强化形态的名称
     *
     * @return 当前强化形态的名称
     */
    public String getActiveAwakeningName() {
        return activeAwakeningName;
    }

    /**
     * 设置当前强化形态的名称
     *
     * @param s 新的强化形态名称
     */
    public void setActiveAwakeningName(String s) {
        this.activeAwakeningName = s;
        markDirty();
    }

    /**
     * 设置当前变身骑士的名称
     *
     * @param riderName 新的骑士名称
     */
    public void setActiveRiderName(String riderName) {
        this.activeRiderName = riderName;
        markDirty();
    }


    /**
     * 检查数据是否脏
     *
     * @return 数据是否脏
     */
    public boolean isDirty() {
        return needsSync;
    }

    // 清除脏数据
    public void clearDirty() {
        this.needsSync = false;
    }

    // 标记数据为脏
    private void markDirty() {
        this.needsSync = true;
        this.needsSave = true;
    }

    /**
     * 序列化玩家数据为NBT标签
     *
     * @return 序列化后的NBT标签
     */
    @Override
    public CompoundTag serializeNBT() {
        CompoundTag nbt = new CompoundTag();
        nbt.putString("State", currentState.name());
        nbt.putString("ActiveRider", activeRiderName);
        nbt.putString("ActiveAwakening", activeAwakeningName);
        nbt.put("StandbyGear", standbyGear);
        nbt.put("ActiveGear", activeGear);
        return nbt;
    }

    /**
     * 从NBT标签反序列化玩家数据
     *
     * @param nbt 包含玩家数据的NBT标签
     */
    @Override
    public void deserializeNBT(CompoundTag nbt) {
        this.currentState = HenshinState.fromName(nbt.getString("State"));
        this.activeRiderName = nbt.getString("ActiveRider");
        this.activeAwakeningName = nbt.getString("ActiveAwakening");

        if (nbt.contains("StandbyGear", 10)) {
            this.standbyGear = nbt.getCompound("StandbyGear");
        }

        if (nbt.contains("ActiveGear", 10)) {
            this.activeGear = nbt.getCompound("ActiveGear");
        }

        // 标记需要恢复状态
        this.needsStateRestore = true;
    }

    /**
     * 从玩家数据加载数据
     *
     * @param player 玩家实例
     */
    public void loadFromPlayer(Player player) {
        CompoundTag persistentData = player.getPersistentData();
        if (persistentData.contains("KamenRiderData", 10)) {
            CompoundTag riderData = persistentData.getCompound("KamenRiderData");
            try {
                deserializeNBT(riderData);
            } catch (Exception e) {
                persistentData.remove("KamenRiderData");
                resetToDefaultState();
            }
        }
    }

    /**
     * 保存玩家数据到玩家实例
     *
     * @param player 玩家实例
     */
    public void saveToPlayer(Player player) {
        player.getPersistentData().put("KamenRiderData", serializeNBT());
    }

    /**
     * 同步玩家数据到客户端
     *
     * @param player 玩家实例
     */
    public void sync(Player player) {
        if (player instanceof ServerPlayer serverPlayer) {
            NetworkHandler.sendToPlayer(
                    new SyncPlayerDataPacket(serializeNBT(), player.getUUID()),
                    serverPlayer
            );
        }
    }

    /**
     * 清除玩家数据
     *
     * @param playerId 玩家UUID
     */
    public static void clearPlayerData(UUID playerId) {
        SERVER_INSTANCES.remove(playerId);
        CLIENT_INSTANCES.remove(playerId);
    }

    // 重置玩家数据为默认状态
    private void resetToDefaultState() {
        this.currentState = HenshinState.INACTIVE;
        this.activeRiderName = "";
        this.standbyGear = new CompoundTag();
        this.activeGear = new CompoundTag();
    }

//    /**
//     * 恢复玩家状态
//     *
//     * @param player 玩家实例
//     */
//    public void restorePlayerState(Player player) {
//        switch (currentState) {
//            case ACTIVE:
//                restoreActiveState(player);
//                break;
//
//            case STANDBY:
//                restoreStandbyState(player);
//                break;
//
//            case ACTIVE_AWAKENING:
//                restoreAwakeningState(player);
//                break;
//
//            default:
//                // 其他状态不需要恢复
//                break;
//        }
//    }
//
//    /**
//     * 恢复基础形态状态
//     */
//    private void restoreActiveState(Player player) {
//        BaseRiderConfig baseConfig = RiderConfigRegistry.getConfig(activeRiderName);
//        if (baseConfig != null) {
//            // 恢复装备
//            CompoundTag activeGear = getActiveGear();
//            if (!activeGear.isEmpty()) {
//                HenshinUtils.restorePlayerGear(player, activeGear);
//            } else {
//                baseConfig.equipFullArmorSet(player);
//            }
//        }
//    }
//
//    /**
//     * 恢复待机前存储的装备
//     */
//    private void restoreStandbyState(Player player) {
//        BaseRiderConfig config = RiderConfigRegistry.getConfig(activeRiderName);
//        if (config != null) {
//            // 恢复腰带
//            CompoundTag standbyGear = getStandbyGear();
//            if (standbyGear.contains("legs")) {
//                player.setItemSlot(EquipmentSlot.LEGS,
//                        ItemStack.of(standbyGear.getCompound("legs")));
//            } else {
//                config.equipBelt(player);
//            }
//        }
//    }
//
//    /**
//     * 恢复强化形态状态
//     */
//    private void restoreAwakeningState(Player player) {
//        BaseRiderConfig baseConfig = RiderConfigRegistry.getConfig(activeRiderName);
//        if (baseConfig instanceof FullRiderConfig fullConfig) {
//            AwakeningConfig awakeningConfig = fullConfig.getAwakeningConfig(activeAwakeningName);
//            if (awakeningConfig != null) {
//                // 恢复装备
//                CompoundTag activeGear = getActiveGear();
//                if (!activeGear.isEmpty()) {
//                    HenshinUtils.restorePlayerGear(player, activeGear);
//                }
//            }
//        }
//    }
//


}